from flask import Blueprint

from app.utils import response_get

project_bp = Blueprint('project1', __name__)


@project_bp.route('/start_project', methods=['GET'])
def get_start_projects():
    user_id = request.args.get('user_id', type=int)
    limit = request.args.get('limit', 10, type=int)
    page = request.args.get('page', 1, type=int)
    sort_by = request.args.get('sort_by', 'project_time')  # 默认按照 project_time 排序
    sorting_order = request.args.get('sorting_order', 'desc')  # 默认升序
    status = request.args.get('status', 'all')  # 默认所有状态
    search = request.args.get('search', None)  # 默认没有搜索过滤

    # 构建查询
    query = Project.query.filter_by(starter_id=user_id)
    if status != 'all':
        query = query.filter_by(project_type=status)
    if search:
        query = query.filter(Project.project_name.like(f'%{search}%'))

    # 排序
    if sorting_order == 'desc':
        query = query.order_by(db.desc(getattr(Project, sort_by)))
    else:
        query = query.order_by(getattr(Project, sort_by))

    # 执行分页查询
    pagination = query.paginate(page=page, per_page=limit, error_out=False)
    projects = pagination.items
    total = pagination.total

    # 构建响应数据
    projects_data = []
    for project in projects:
        # 获取项目发起人信息
        starter = User.query.get(project.starter_id)
        # 获取合作者信息
        cooperator_list = []
        if project.cooperator_id_list:
            cooperator_ids = project.cooperator_id_list.split(',')
            for cooperator_id in cooperator_ids:
                cooperator = User.query.get(int(cooperator_id))
                if cooperator:
                    cooperator_list.append({
                        "cooperator_id": cooperator.user_id,
                        "cooperator_name": cooperator.user_name,
                        "cooperator_avatar": cooperator.avatar_url,
                    })

        projects_data.append({
            "project_id": project.project_id,
            "project_name": project.project_name,
            "starter": {
                "starter_id": starter.user_id if starter else None,
                "starter_name": starter.user_name if starter else '',
                "starter_avatar": starter.avatar_url if starter else '',
            },
            "cooperator_list": cooperator_list,
            "project_time": project.project_time.strftime('%Y-%m-%d %H:%M:%S') if project.project_time else '',
            "project_describe": project.project_description,
        })

    response_data = {
        "code": 200,
        "data": projects_data,
        "pagination": {
            "page": page,
            "perpage": limit,
            "total": total
        }
    }

    return response_get(200, response_data)


@project_bp.route('/participate_project', methods=['GET'])
def get_participate_projects():
    user_id = request.args.get('user_id', type=int)
    limit = request.args.get('limit', 10, type=int)
    page = request.args.get('page', 1, type=int)
    sort_by = request.args.get('sort_by', 'project_time')  # 默认按项目时间排序
    sorting_order = request.args.get('sorting_order', 'desc')  # 默认升序
    status = request.args.get('status', 'all')  # 默认所有状态
    search = request.args.get('search', None)  # 默认无搜索条件
    print(user_id, limit, page, sort_by, sorting_order)
    # 构建查询
    query = Project.query.filter(Project.cooperator_id_list.contains(str(user_id)))
    if status != 'all':
        query = query.filter_by(project_type=status)
    if search:
        query = query.filter(Project.project_name.like(f'%{search}%'))

    # 排序
    if sorting_order == 'desc':
        query = query.order_by(db.desc(getattr(Project, sort_by)))
    else:
        query = query.order_by(getattr(Project, sort_by))

    # 执行分页查询
    pagination = query.paginate(page=page, per_page=limit, error_out=False)
    projects = pagination.items
    total = pagination.total

    # 构建响应数据
    projects_data = []
    for project in projects:
        starter = User.query.get(project.starter_id)
        cooperator_list = []
        if project.cooperator_id_list:
            cooperator_ids = project.cooperator_id_list.split(',')
            for cooperator_id in cooperator_ids:
                cooperator = User.query.get(int(cooperator_id))
                if cooperator:
                    cooperator_list.append({
                        "cooperator_id": cooperator.user_id,
                        "cooperator_name": cooperator.user_name,
                        "cooperator_avatar": cooperator.avatar_url,
                    })

        projects_data.append({
            "project_id": project.project_id,
            "project_name": project.project_name,
            "starter": {
                "starter_id": starter.user_id if starter else None,
                "starter_name": starter.user_name if starter else '',
                "starter_avatar": starter.avatar_url if starter else '',
            },
            "cooperator_list": cooperator_list,
            "project_type": project.project_type,
            "project_time": project.project_time.strftime('%Y-%m-%d %H:%M:%S') if project.project_time else '',
            "project_describe": project.project_description,
        })

    response_data = {
        "code": 200,
        "data": projects_data,
        "pagination": {
            "page": page,
            "perpage": limit,
            "total": total
        }
    }

    return response_get(200, response_data)


from datetime import datetime


@project_bp.route('/create_project', methods=['POST'])
def create_project():
    starter_id = request.args.get('starter_id')
    cooperator_id_list = request.args.get('cooperator_id_list', '')
    project_name = request.args.get('project_name')
    project_describe = request.args.get('project_describe')
    project_type = request.args.get('project_type')
    print(starter_id, cooperator_id_list, project_name)
    # 检查必要的字段是否提供
    if not all([starter_id, project_name, project_type]):
        return response(400, {'message': 'Missing required fields'})

    # 创建新的项目实例
    new_project = Project(
        starter_id=starter_id,
        cooperator_id_list=cooperator_id_list,
        project_name=project_name,
        project_description=project_describe,
        project_type=project_type,
        project_time=datetime.utcnow(),
        project_state='stop',
        project_model='{"nodes":[],"endpoints":[],"edges":[],"head":""}'
    )

    # 添加到数据库
    db.session.add(new_project)
    db.session.commit()

    # 返回成功响应
    return response(200)


@project_bp.route('/project_cooperator', methods=['GET'])
def get_project_cooperators():
    # 从查询参数中获取user_id
    user_id = request.args.get('user_id', type=int)

    # 查询数据库以获取除了指定user_id之外的所有用户
    cooperators = User.query.filter(User.user_id != user_id).all()

    # 构建响应数据
    cooperators_data = [
        {
            "cooperator_id": cooperator.user_id,
            "cooperator_name": cooperator.user_name,
            "cooperator_avatar": cooperator.avatar_url,
        }
        for cooperator in cooperators
    ]

    response_data = {
        "code": 200,
        "data": cooperators_data
    }

    return jsonify(response_data)


@project_bp.route('/get_model', methods=['GET'])
def get_model():
    project_id = request.args.get('project_id', type=int)  # 从请求的查询参数中获取project_id

    if not project_id:
        return response(400)  # 如果没有提供project_id，则返回400错误

    project = Project.query.get(project_id)  # 从数据库中查询对应的Project实例

    if not project:
        return response(404)  # 如果没有找到对应的项目，则返回404错误

    return response(200, {'project_model': project.project_model})  # 返回成功的响应，包含从数据库中检索到的project_model字段


from flask import Blueprint, request, jsonify
from app import db
from app.models import Project, Dataset, Apply, User
from app.utils import response


@project_bp.route('/get_dataset', methods=['GET'])
def get_dataset():
    project_id = request.args.get('project_id', type=int)
    if not project_id:
        return response(400)
    print(project_id)
    project = Project.query.get(project_id)
    if not project:
        return response(400)

    # 获取项目发起者的数据集
    starter_datasets = Dataset.query.filter_by(user_id=project.starter_id, dataset_state='public').all()
    print(project.starter_id)
    # 获取项目参与者ID列表
    participant_ids = project.cooperator_id_list.split(',') if project.cooperator_id_list else []
    print(participant_ids)
    # 转换为整数
    participant_ids = [int(pid) for pid in participant_ids if pid.isdigit()]
    # participant_ids.insert(0, project.starter_id)
    # print(participant_ids)
    # 获取项目参与者的数据集
    # participant_datasets = Dataset.query.filter(Dataset.user_id.in_(participant_ids),
    #                                             Dataset.dataset_state == 'public').all()
    participant_datasets = Dataset.query.filter(Dataset.user_id.in_(participant_ids)).all()
    print(participant_datasets)
    # 合并发起者和参与者的数据集
    all_datasets = starter_datasets + participant_datasets
    print(all_datasets)
    response_datas = []
    user = User.query.get(project.starter_id)
    datasets_data = []
    for dataset in starter_datasets:
        datasets_data.append({
            'dataset_id': dataset.dataset_id,
            'dataset_name': dataset.dataset_name,
            'dataset_use': dataset.dataset_use,
            'dataset_describe': dataset.dataset_describe,
            'dataset_address': dataset.dataset_address,
        })
    response_data = {
        'user_id': user.user_id,
        'user_name': user.user_name,
        'avatar_url': user.avatar_url,
        'ip': user.ip,
        'data_set': datasets_data
    }
    response_datas.append(response_data)
    for user_id in participant_ids:
        # 过滤出已通过申请的数据集
        approved_datasets = []
        for dataset in all_datasets:
            apply = Apply.query.filter_by(applicant_id=project.starter_id, dataset_id=dataset.dataset_id,
                                          apply_state='approve').first()
            if apply:
                approved_datasets.append(dataset)

        # 构建响应数据
        datasets_data = []
        for dataset in approved_datasets:
            if dataset.user_id == user_id:
                datasets_data.append({
                    'dataset_id': dataset.dataset_id,
                    'dataset_name': dataset.dataset_name,
                    'dataset_use': dataset.dataset_use,
                    'dataset_describe': dataset.dataset_describe,
                    'dataset_address': dataset.dataset_address,
                })

        # 获取项目发起者信息
        user = User.query.get(user_id)

        response_data = {
            'user_id': user.user_id,
            'user_name': user.user_name,
            'avatar_url': user.avatar_url,
            'ip':user.ip,
            'data_set': datasets_data
        }
        response_datas.append(response_data)
    print(response_datas)
    return response(200, response_datas)


@project_bp.route('/save_model', methods=['POST'])
def save_model():
    # 从请求体中获取project_id和project_model
    project_id = request.args.get('project_id', type=int)
    project_model = request.args.get('project_model')

    # 校验参数
    if not project_id or project_model is None:
        return response(400, {'message': 'Missing required parameters'})

    # 查找对应的项目
    project = Project.query.get(project_id)
    if not project:
        return response(404, {'message': 'Project not found'})

    # 更新项目的project_model字段
    project.project_model = project_model
    db.session.commit()  # 提交更改到数据库

    return response(200, {'message': 'Project model updated successfully'})


@project_bp.route('/change_model', methods=['POST'])
def change_model():
    # 从请求中获取project_id和project_state
    project_id = request.args.get('project_id', type=int)
    project_state = request.args.get('project_state')

    # 校验参数
    if not project_id or not project_state:
        return response(400, {'message': 'Missing required parameters'})

    # 查找对应的项目
    project = Project.query.get(project_id)
    if not project:
        return response(404, {'message': 'Project not found'})

    # 更新项目状态
    project.project_state = project_state
    db.session.commit()  # 提交更改到数据库

    return response(200, {'message': 'Project state updated successfully'})
